#include "Ad7680.h"
#include <unistd.h>
#include <fcntl.h>
#include <thread>
#include <queue>
#include "SpiUserspace.h"
#include "stdio.h"

static const int AD_DATA_MAX = 65535;
static const int AVERAGE_TOTAL_NUM = 10;
//static float averageAdRatio = 0;
static int adDataNow = 0;
static int adDataAverage = 0;

int AdSpiRead()
{
    uint8_t bits = 8;
    uint32_t speedMax = 25000000;
    uint16_t delay = 0;
    static uint32_t mode;
    mode |= SPI_CPOL;
//    mode |= SPI_CPHA;
    int fd = open("/dev/spidev4.0", O_RDWR);
    if (fd < 0)
    {
        printf("can't open device");
        return fd;
    }
    int ret = SpiSetOpt(fd, bits,speedMax,mode);
    if(ret<1)
    {
        printf("error");
        return ret;
    }

    const long AD_MAX_SPI_SCLK = 2500000;
    int adDataSum = 0;
    std::queue<int> adDataQueue;
    while(true)
    {
        int BUFFER_SIZE = 3;
        uint8_t buf[BUFFER_SIZE];
        ret = SpiRead(fd,buf,BUFFER_SIZE,delay,AD_MAX_SPI_SCLK,bits,mode);
        if(ret<1)
        {
            printf("error");
            return ret;
        }
        adDataNow = ((buf[0]&0x0F)<<12)+(buf[1]<<4)+((buf[2]&0xF0)>>4);
        //int data = ((buf[0])<<12)+(buf[1]<<4)+((buf[2])>>4);


//        float ratio = adData*1.0/65535;
//        printf("after cycle adread, addata is %d\n",adData);
//        printf("after cycle adread, ratio is %f\n",ratio);

        adDataSum+=adDataNow;
        adDataQueue.push(adDataNow);
        while(adDataQueue.size()>AVERAGE_TOTAL_NUM)
        {
            adDataSum-=adDataQueue.front();
            adDataQueue.pop();
        }
        adDataAverage = adDataSum/adDataQueue.size();
        //printf("the average %d ad data is %d\n",adDataQueue.size(),adAverageData);
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    close(fd);
    return 1;
}

float GetAdRatioNow()
{
    return (static_cast<float>(adDataNow)/AD_DATA_MAX);
}

float GetAdRatioAverage()
{
    return (static_cast<float>(adDataAverage)/AD_DATA_MAX);
}


